﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MutiCodecO.codeclib
{
    class Asii2Url : ICodec
    {
        private char IntToHex(int n)
        {
            if (n <= 9)
            {
                return (char)((ushort)(n + 0x30));
            }
            return (char)((ushort)((n - 10) + 0x41));
        }

        private bool IsSafe(char ch)
        {
            if ((((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z'))) || ((ch >= '0') && (ch <= '9')))
            {
                return true;
            }
            switch (ch)
            {
                case '\\':
                case '(':
                case ')':
                case '*':
                case '-':
                case '.':
                case '_':
                case '!':
                    return true;
            }
            return false;
        }

        public String parse(String strInput)
        {
            byte[] bytesInput = Encoding.Default.GetBytes(strInput);
            StringBuilder strRslt = new StringBuilder();
            for (int i = 0; i < bytesInput.Length; i++)
            {
                if (IsSafe(Convert.ToChar(bytesInput[i])))
                {
                    strRslt.Append(Convert.ToChar(bytesInput[i]));
                }
                else
                {
                    strRslt.Append('%');
                    int c = (int)bytesInput[i];
                    strRslt.Append(IntToHex(c / 16));
                    strRslt.Append(IntToHex(c % 16));
                }
            }
            return strRslt.ToString();
        }

        public String parse(String strInput, String prefix, String partion)
        {
            byte[] bytesInput = Encoding.Default.GetBytes(strInput);
            StringBuilder strRslt = new StringBuilder();
            for (int i = 0; i < bytesInput.Length; i++)
            {
                strRslt.Append(prefix);
                if (IsSafe(Convert.ToChar(bytesInput[i])))
                {
                    strRslt.Append(Convert.ToChar(bytesInput[i]));
                }
                else
                {
                    strRslt.Append('%');
                    int c = (int)bytesInput[i];
                    strRslt.Append(IntToHex(c / 16));
                    strRslt.Append(IntToHex(c % 16));
                }
                if (i != bytesInput.Length - 1)
                    strRslt.Append(partion);
            }
            return strRslt.ToString();
        }
    }
}
